package cn.aib.msm.controller;

import cn.aib.commonutils.R;
import cn.aib.msm.service.MsmService;
import cn.aib.msm.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm/msm")
//@CrossOrigin
@Slf4j
public class MsmController {

    @Resource
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     *  短信发送
     *  方法名：sendMessage
     *  参数：String phone（手机号码）
     *  返回值 R
     */
    @GetMapping("send/{phone}")
    public R sendMessage(@PathVariable String phone){
        //根据手机号码查询redis中是否存在验证码，若有代表未过期
        String code = redisTemplate.opsForValue().get(phone);

        if(!StringUtils.isEmpty(code)){
            //若验证码不为空，则不发送短信
            return R.ok();
        }

        //生成验证码
        code = RandomUtil.getSixBitRandom();

        //设置验证码到map中
        HashMap<String, Object> params = new HashMap<>();

        params.put("code", code);

        //调用service完成短信发送
        boolean flag = msmService.sendCodeMessage(params,phone);
        if(flag){
            //若发生成功，验证码保存到redis
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

            return R.ok();
        }else {
            return R.error();
        }

    }
}
